#!/bin/env python3
import pytz
import datetime
import PyRSS2Gen
import requests
from quart import Quart, abort

app = Quart(__name__)
tz = pytz.timezone('Asia/Shanghai')
utc = pytz.utc
version = '1.1.0'


def timeconvert(time):
    time = str(time).split('+')[0].split('T')
    date = time[0].split('-')
    time = time[1].split(':')
    time = datetime.datetime(int(date[0]), int(date[1]), int(
        date[2]), int(time[0]), int(time[1]), int(time[2]))
    return time.astimezone(utc)


def buildtitle(item):
    title = f"【{item['type']['name']}】{item['subject']}"
    if item['top'] == 1:
        title = '【置顶】' + title
    return title


def builddescription(item, browser_h='700px'):
    return f'''<iframe height="{browser_h}" width="100%" src="https://bbs.deepin.org/post/{item['id']}">'''
    # return f"{item['forum']['name']} {item['user']['nickname']} · {item['updated_at_desc']} 最后回复{item['last_date_desc']} {item['views_cnt']}浏览 {item['posts_cnt']}评论"


@app.route('/favicon.ico')
async def favicon():
    return ""


@app.route('/')
@app.route('/<int:limit>')
@app.route('/<int:limit>/<string:browser_h>')
@app.route('/<int:limit>/<string:browser_h>/<string:whare>')
async def root(whare='', limit=100, browser_h='700px'):
    url = f'https://bbs.deepin.org/api/v1/thread/index?order=updated_at&limit={str(limit)}&where={whare}&offset=0'
    headers = {'user-agent': f'daze/DFRC/{version}'}
    deepin = requests.get(url=url, headers=headers)
    if deepin.status_code != 200:
        abort(deepin.status_code)
    else:
        deepin = deepin.json()
        deepin = deepin['ThreadIndex']
        if not deepin:
            abort(404)
        items = []
        for item in deepin:
            url = 'https://bbs.deepin.org/post/' + str(item['id'])
            items.append(PyRSS2Gen.RSSItem(title=buildtitle(item),
                                           link=url,
                                           description=builddescription(
                                               item, browser_h),
                                           author=item['user']['nickname'],
                                           guid=PyRSS2Gen.Guid(url),
                                           pubDate=timeconvert(item['updated_at'])))
        last = None
        for l in deepin:
            if l['top'] != 1:
                last = timeconvert(l['updated_at'])
                break
        if not last:
            last = timeconvert(deepin[0]['updated_at'])
        if whare == 'hot_value':
            title = '深度论坛 - 热门帖子'
        elif whare == 'is_digest':
            title = '深度论坛 - 精华帖子'
        else:
            title = '深度论坛'
        rss = PyRSS2Gen.RSS2(
            title=title,
            link="https://bbs.deepin.org/index",
            description="由DFRC提供的适用于Deepin新版论坛的RSS订阅源",
            lastBuildDate=last,
            items=items,
            generator=f'DFRC {version}',
            docs="https://appstore.zdatek.top/daze/DFRC")
    return rss.to_xml("utf-8"), 200, [('content-type', 'application/xml; charset=utf-8')]

print(f' * DFRC {version} Starting....')